<template>
  <fl-navBar
    dark
    :border="false"
    fixed
    background-color="transparent"
    status-bar
    left-icon="left"
  />
  <view class="login_form">
    <view class="hello">您好，</view>
    <view class="welcome">欢迎登录</view>

    <view class="form_box">
      <!-- 手机验证码 -->
      <view v-if="loginType === '1'">
        <view class="form_item">
          <input
            maxlength="11"
            v-model="formCode.phonenumber"
            placeholder="请输入11位手机号码"
          />
        </view>
        <view class="form_item">
          <input v-model="formCode.smsCode" placeholder="请输入验证码" />
          <button
            plain
            class="code"
            :disabled="state.counting"
            @tap.stop="startCountdown"
          >
            {{ state.counting ? `剩余 ${state.countdown} 秒` : "获取验证码" }}
          </button>
        </view>
      </view>
      <!-- 账号密码 -->
      <view v-if="loginType === '2'">
        <view class="form_item">
          <text class="userIcon iconfont icon-yonghuming"></text>
          <input maxlength="15" v-model="loginForm.username" placeholder="请输入账号" />
          <text
            @tap="close('username')"
            v-show="loginForm.username.length > 0"
            class="close_icon iconfont icon-guanbishixin"
          ></text>
        </view>
        <view class="form_item">
          <text class="userIcon iconfont icon-emimima"></text>
          <input
            maxlength="15"
            v-model="loginForm.password"
            :password="showPassword"
            placeholder="请输入密码"
          />
          <text
            @tap="changeEyes"
            :class="showPassword ? 'icon-biyanjing' : 'icon-icon-eye-open'"
            class="eye_icon iconfont"
          ></text>
          <text
            @tap="close('password')"
            v-show="loginForm.password.length > 0"
            class="close_icon iconfont icon-guanbishixin"
          ></text>
        </view>
      </view>
      <!-- #ifdef MP-WEIXIN -->
      <view class="submitBtn_login" @tap="loading ? null : handleLogin()">登录</view>
      <!-- #endif -->
      <!-- #ifdef H5 -->
      <up-button
        :loading="loading"
        @tap="handleLogin"
        loadingText="登录中"
        class="submitBtn_login"
        type="primary"
        text="登录"
      ></up-button>
      <!-- #endif -->
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, reactive } from "vue";
import modal from "@/plugins/modal";
import { onLoad } from "@dcloudio/uni-app";
import { getCodeImg } from "@/api/login/login";
import CryptoJS from "crypto-js";
import { encrypt, decrypt } from "@/utils/jsencrypt";
import { smsCode } from "@/api/http";
import store from "@/store";
const loginType = ref("");
const formCode = ref({});
const state = reactive({
  counting: false,
  countdown: 60,
});
const loginForm = ref({
  username: "",
  password: "",
  code: "",
  key: "",
  iv: "",
  uuid: "",
});
onLoad((options) => {
  loginType.value = options.type;
});
const loading = ref(false);
const showPassword = ref(true);
async function handleLogin() {
  if (loginType.value === "1") {
    // 验证码 功能
    const phoneReg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
    if (!formCode.value.phonenumber) return modal.msgError("请输入11位手机号");
    if (!phoneReg.test(formCode.value.phonenumber))
      return modal.msgError("手机号格式错误");
    if (!formCode.value.smsCode) return modal.msgError("请输入验证码");
    loading.value = true;
    modal.loading("登录中...");
    handleLoginForm();
  } else if (loginType.value === "2") {
    if (loginForm.value.username === "") {
      modal.msgError("请输入您的账号");
    } else if (loginForm.value.password === "") {
      modal.msgError("请输入您的密码");
    } else {
      loading.value = true;
      modal.loading("登录中...");
      handleLoginForm();
    }
  }
}

async function handleLoginForm() {
  if (loginType.value === "1") {
    // 验证码
    CodeLogin(formCode.value);
    return;
  }
  // 密码
  let res = await getCodeImg();
  if (res.data) {
    let newForm = { ...loginForm.value };
    newForm.uuid = res.data.uuid;
    newForm.key = res.data.key;
    newForm.iv = res.data.iv;
    newForm.password = aesEncrypt(newForm.key, newForm.iv, newForm.password);

    newForm.username = aesEncrypt(newForm.key, newForm.iv, newForm.username);
    // 调用action的登录方法
    pwdLogin(newForm);
  } else {
    handleLoginForm();
  }
}
// 密码登录
async function pwdLogin(newForm) {
  store
    .dispatch("Login", newForm)
    .then(() => {
      loading.value = false;
      modal.closeLoading();
      loginSuccess();
    })
    .catch(() => {
      modal.closeLoading();
      loading.value = false;
    });
}
// 验证码登录
async function CodeLogin(newForm) {
  store
    .dispatch("codeLogin", newForm)
    .then(() => {
      loading.value = false;
      modal.closeLoading();
      loginSuccess();
    })
    .catch(() => {
      modal.closeLoading();
      loading.value = false;
    });
}

function aesEncrypt(key, iv, word) {
  let srcs = CryptoJS.enc.Utf8.parse(word);
  let encrypted = CryptoJS.AES.encrypt(srcs, CryptoJS.enc.Utf8.parse(key), {
    iv: CryptoJS.enc.Utf8.parse(iv),
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7,
  });
  return CryptoJS.enc.Base64.stringify(encrypted.ciphertext);
}
const close = (e) => {
  loginForm.value[e] = "";
};
function loginSuccess() {
  // 设置用户信息
  store.dispatch("GetInfo").then(async (res) => {
    await store.dispatch("getMenus")
    modal.msgSuccess("登录成功");
    uni.switchTab({
      url: "/pages/business/index",
    });
    // uni.navigateTo({ url: '/pages/surveyEvaluation/quesFilling' })
  });

}
function changeEyes() {
  showPassword.value = !showPassword.value;
}
const startCountdown = async () => {
  const phoneReg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
  if (!formCode.value.phonenumber) return modal.msgError("请输入11位手机号");
  if (!phoneReg.test(formCode.value.phonenumber)) return modal.msgError("手机号格式错误");
  if (state.counting) return;
  state.counting = true;
  //发送验证码
  let par = {
    phonenumber: formCode.value.phonenumber,
  };
  await smsCode(par);

  const timer = setInterval(() => {
    state.countdown--;
    if (state.countdown === 0) {
      clearInterval(timer);
      state.counting = false;
      state.countdown = 60;
    }
  }, 1000);
};
onMounted(() => {});
</script>

<style lang="scss">
page {
  display: flex;
  flex-direction: column;
  height: 100%;
  // overflow: hidden;
  // background-color: #3bbae9;
  background: url("@/static/images/loginform_back.png") no-repeat;
  background-size: 100% auto;
}

.login_form {
  padding-top: 40rpx;

  .hello {
    font-size: 50rpx;
    font-weight: 700;
    color: #fff;
    padding-left: 48rpx;
  }

  .welcome {
    font-size: 40rpx;
    color: #fff;
    padding-left: 48rpx;
    margin-top: 12rpx;
  }

  .form_box {
    width: 750rpx;
    height: 100%;
    border-radius: 66rpx 66rpx 0 0;
    background-color: #fff;
    margin-top: 50rpx;
    padding-top: 96rpx;

    .form_item {
      overflow: hidden;
      position: relative;
      display: flex;
      align-items: center;
      width: 650rpx;
      height: 88rpx;
      border-radius: 44rpx;
      background-color: #f1f7fc;
      margin: 0 auto 32rpx;
      padding-left: 80rpx;
      box-sizing: border-box;

      .close_icon {
        position: absolute;
        top: 49%;
        right: 20rpx;
        transform: translateY(-50%);
        color: #aba8a8;
        font-size: 48rpx;
      }

      .userIcon {
        position: absolute;
        top: 50%;
        transform: translateY(-50%);
        left: 35rpx;
        font-size: 30rpx;
        color: gray;
      }

      .eye_icon {
        position: absolute;
        top: 50%;
        transform: translateY(-50%);
        width: 60rpx;
        height: 60rpx;
        right: 100rpx;
        font-size: 40rpx;
        text-align: center;
        line-height: 60rpx;
        color: gray;
      }

      button {
        background-color: transparent;
        border: none;
      }

      .code {
        position: absolute;
        top: 0;
        right: 0;
        width: 180rpx;
        height: 88rpx;
        color: #333;
        font-size: 28rpx;
        text-align: left;
        line-height: 88rpx;
        padding: 0;
      }

      input {
        width: 400rpx;
        height: 88rpx;
        color: #999999;
        font-size: 30rpx;
      }
    }

    .submitBtn_login {
      width: 650rpx;
      height: 88rpx;
      text-align: center;
      line-height: 88rpx;
      background-color: #0d80d7;
      color: #fff;
      font-size: 36rpx;
      border-radius: 44rpx;
      margin: 100rpx auto 0;
    }
  }
}
</style>
